package com.lft.cryptology02.kaiser01;

public class KaiserDemo2 {
    public static void main(String[] args) {
        // 明文
        String str = "Hello World";
        System.out.println("明文: " + str);
        String encryptKaiser = encryptKaiser(str, 5);
        // 打印密文
        System.out.println("密文: " + encryptKaiser);
        
        System.out.println("============================");
        
        String decryptKaiser = decryptKaiser(encryptKaiser, 5);
        System.out.println("解密后的明文：" + decryptKaiser);
    }
    
    /**
     * 凯撒加密
     * @param original 明文
     * @param shift    移位量
     * @return 密文
     */
    public static String encryptKaiser(String original, Integer shift) {
        // 用于拼接
        StringBuilder builder = new StringBuilder();
        
        // 将字符串转换成字节数组
        char[] charArray = original.toCharArray();
        for (char c : charArray) {
            int ascii = c;
            // 移位加密
            ascii += shift;
            // 转成新字符
            char newChar = (char) ascii;
            // 拼接
            builder.append(newChar);
        }
        return builder.toString();
    }
    
    /**
     * 凯撒解密
     * @param encryptedData 密文
     * @param shift         移位量
     * @return 明文
     */
    public static String decryptKaiser(String encryptedData, Integer shift) {
        // 用于拼接
        StringBuilder builder = new StringBuilder();
        
        // 将字符串转换成字节数组
        char[] charArray = encryptedData.toCharArray();
        for (char c : charArray) {
            int ascii = c;
            // 移位加密
            ascii -= shift;
            // 转成新字符
            char newChar = (char) ascii;
            // 拼接
            builder.append(newChar);
        }
        return builder.toString();
    }
}
